<?php

namespace app\api\controller\haipi;

use app\admin\model\UserMoneyLog;
use app\common\controller\Frontend;
use app\common\model\Agent;
use app\common\model\CommissionLog;
use app\common\model\haipi\Order;
use app\common\model\user\Vip;
use app\common\model\user\VipExpire;
use think\facade\Db;
use app\api\service\OrderService;

class User extends Frontend
{
    protected array $noNeedLogin = [];

    protected array $noNeedPermission = ['index'];

    public function initialize(): void
    {
        parent::initialize();
    }


    public function userinfo(){
       $data = $this->auth->getUserInfo();
       $user = $this->auth->getUser();
       $vipRecord = $user->userVipExpire();
       $vip = null;
       if($vipRecord){
            $vip = [
                'name' => $vipRecord->vip['name'],
                'is_long' => $vipRecord['is_long'],
                'expire_time' => $vipRecord['expire_time']
            ];
       }

       $this->success('', [
            'userInfo' => $data,
            'vip' => $vip
        ]);
    }


    /**
     * vip 等级
     * @return void
     */
    public function vipLevels(){
        $data = Vip::where('status', 1)->order('weigh', 'desc')->select();
        $this->success('', $data);
    }


    public function upVipByBalance(){
        // 使用验证器验证参数
        $validate = new \app\api\validate\VipValidate();
        $data = $this->request->post();
        if (!$validate->scene('upVip')->check($data)) {
            $this->error($validate->getError());
        }

        $vipId = $data['vip_id'];
        $userinfo = $this->auth->getUser();
        
        // 检查VIP是否存在
        $vipLevel = $validate->checkVipExists($vipId);
        if (!$vipLevel) {
            $this->error('参数不正确');
        }
        
        // 检查用户余额是否足够
        if (!$validate->checkUserBalance($userinfo, $vipLevel)) {
            $this->error('余额不足');
        }
        
        // 检查用户是否已经是永久会员
        if (!$validate->checkUserVipStatus($userinfo)) {
            $this->error('您已经是永久会员了');
        }

        $orderService = new OrderService();
    
        Db::transaction(function()use($vipLevel,$userinfo, $orderService){
            //创建订单
            $traceNo = $orderService->generateUniqueNo();
            $order = $orderService->createOrder($userinfo->id, $vipLevel->sale_price, Order::GOODS_TYPE_VIP, $vipLevel->id, Order::PAY_TYPE_BALANCE,$traceNo);

            //处理 VIP 信息
            $orderService->handleVip($userinfo, $vipLevel);
            
            //余额
            $this->handleUserBalance($userinfo->id, $vipLevel->sale_price);

            // 佣金
            $orderService->handleCommission($userinfo , $order);
        });
       
        $this->success('升级成功');
    }

    protected function handleUserBalance($userId, $amount){
        UserMoneyLog::create([
            'memo' => '升级会员',
            'money' => -$amount,
            'user_id' => $userId
        ]);
    }


}